package com.hxd.qzg.common;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.hxd.qzg.common.enums.MsgTypeEnum;
import com.hxd.qzg.common.model.Box;
import com.hxd.qzg.common.model.BoxLock;
import com.hxd.qzg.common.model.Qz;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class UseBox {
	private static final Log logger = LogFactory.get();
	private static final String LOCK_TIME = "LOCK_TIME";

	// 锁
	private boolean lock(String account, Integer boxId) {
		BoxLock boxLock = new BoxLock();
		boxLock.setBoxId(boxId);
		boxLock.setLockAccount(account);
		Calendar nowTime = Calendar.getInstance();
		nowTime.setTime(new Date());
		String lockTime = SbhFactory.getLockTime(LOCK_TIME);
		nowTime.add(Calendar.MINUTE, Integer.valueOf(lockTime));
		Date date = nowTime.getTime();
		boxLock.setUnLockTime(date);
		return boxLock.save();
	}

	// 查看锁 是不是当前操作人持有
	private boolean selectlock(String account, Integer boxId) {

		Box box = Box.dao.findById(boxId);
		if (box == null) {
			throw new ServiceException("找不到柜子数据");
		}
		Record record = Db.findFirst("SELECT *  FROM  api_box_lock WHERE   box_id= ?", boxId);

		if (record == null) {
			boolean bl = lock(account, boxId);
			if (!bl) {
				throw new ServiceException("当前柜子正在被客户或者管理员操作,请等待一会");
			}
			return bl;
		}

		String lockAccount = record.getStr("lock_account");
		logger.info("lockAccount {}  account {} ", lockAccount, account);

		if (account.equals(lockAccount)) {
			return true;
		}
		return false;
	}

	// 手机端 查看锁 是不是当前操作人持有
	public boolean operation(String account, String boxId, Integer code, String operation) {
		Integer boxIdInteger = Integer.valueOf(boxId);

		Qz qz = new Qz();
		qz.setBoxId(boxIdInteger);
		qz.setRequest(MsgTypeEnum.getDescription(code));
		qz.setOperation(operation);
		qz.setAccount(account);
		saveQzLog(qz);
		boolean bl =true;
		try {
			 bl = selectlock(account, boxIdInteger);
			logger.info("bl {} ", bl);
			if (bl) {
				Record record = Db.findFirst("SELECT *  FROM  api_box_lock WHERE   box_id= ?", boxId);
				if (null == record) {
					return false;
				}
				BoxLock boxLock = new BoxLock();
				boxLock.setId(record.getInt("id"));
				boxLock.setCode(code);
				boxLock.setOperation(operation);
				bl = boxLock.update();

				return true;
			}
		} catch (Exception e) {
			logger.info("Exception {} ", e.getMessage());
			return false;
		}
		return bl;
	}

	// 客户端 查看锁 是不是当前操作人持有
	public boolean operation(String account, String boxId, Integer code, Operation operation) {
		Integer boxIdInteger = Integer.valueOf(boxId);

		Qz qz = new Qz();
		qz.setBoxId(boxIdInteger);
		qz.setRequest(MsgTypeEnum.getDescription(code));
		String jsonStr = JSONObject.toJSONString(operation);
		qz.setOperation(jsonStr);
		qz.setAccount(account);
		qz.setName(operation.getName());
		saveQzLog(qz);

		boolean bl = selectlock(account, boxIdInteger);
		if (!bl) {
			throw new ServiceException("当前柜子被占用");
		}
		Record record = Db.findFirst("SELECT *  FROM  api_box_lock WHERE   box_id= ?", boxIdInteger);
		BoxLock boxLock = new BoxLock();
		boxLock.setId(record.getInt("id"));
		boxLock.setCode(code);

		boxLock.setOperation(jsonStr);
		bl = boxLock.update();

		return bl;
	}

	public void saveQzLog(Qz qz) {
		ExecutorService executorService = Executors.newSingleThreadExecutor();
		Runnable runnable = new Runnable() {
			public void run() {
				if (qz == null) {
					logger.info("qz is null ");
					return;
				}
				qz.setLastDate(new Date());
				qz.setUpdateTime(new Date());
				qz.setCreateTime(new Date());
				qz.save();
			}
		};
		try {
			executorService.submit(runnable).get();
		} catch (InterruptedException e) {

		} catch (ExecutionException e) {

		}
	}



	// 客户端
	public boolean clickOperation(Operation operation, Integer code) {

		if (null == operation.getBoxId()) {
			throw new ServiceException("Operation is null");

		}
		if (null == code) {
			throw new ServiceException("code is null");

		}
		if (null == operation.getIdcard() && null == operation.getUserId()) {
			throw new ServiceException("Idcard and userId  is null");
		}
		String account = "";
		if (StringUtils.isNotEmpty(operation.getIdcard())) {
			account = operation.getIdcard();
		} else {
			account = String.valueOf(operation.getUserId());
		}
		boolean bl = new UseBox().operation(account, operation.getBoxId(), code, operation);
		return bl;
	}
}
